package com.sc.security.mobile;

import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author sc
 * Created on  2018/1/17
 */
@Data
public class SmsCodeAuthProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthToken smsCodeAuthToken = (SmsCodeAuthToken) authentication;
        UserDetails userDetails = userDetailsService.loadUserByUsername((String) authentication.getPrincipal());
        if(userDetails==null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        SmsCodeAuthToken res = new SmsCodeAuthToken(userDetails,userDetails.getAuthorities());
        res.setDetails(smsCodeAuthToken.getDetails());
        return res;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthToken.class.isAssignableFrom(aClass);
    }
}
